import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Tag,
  Progress,
  message,
  Row,
  Col,
  Statistic,
  Typography,

} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  RobotOutlined,
  ArrowUpOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;
const { Search, TextArea } = Input;

// 关键词数据接口
interface Keyword {
  id: string;
  keyword: string;
  category: string;
  priority: 'HIGH' | 'MEDIUM' | 'LOW';
  optimizationStatus: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'FAILED';
  adoptionRate: number;
  searchVolume: number;
  difficulty: number;
  createdAt: string;
  description?: string;
}

// 优先级配置
const priorityConfig = {
  HIGH: { color: 'red', text: '高' },
  MEDIUM: { color: 'orange', text: '中' },
  LOW: { color: 'green', text: '低' },
};

// 状态配置
const statusConfig = {
  PENDING: { color: 'default', text: '待处理' },
  IN_PROGRESS: { color: 'processing', text: '处理中' },
  COMPLETED: { color: 'success', text: '已完成' },
  FAILED: { color: 'error', text: '失败' },
};

const KeywordManagement: React.FC = () => {
  const [keywords, setKeywords] = useState<Keyword[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingKeyword, setEditingKeyword] = useState<Keyword | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  // 模拟数据
  const mockKeywords: Keyword[] = [
    {
      id: '1',
      keyword: 'AI智能优化',
      category: '人工智能',
      priority: 'HIGH',
      optimizationStatus: 'COMPLETED',
      adoptionRate: 0.85,
      searchVolume: 12500,
      difficulty: 7.5,
      createdAt: '2024-01-15',
      description: '专注于AI技术在业务优化中的应用',
    },
    {
      id: '2',
      keyword: '机器学习算法',
      category: '人工智能',
      priority: 'MEDIUM',
      optimizationStatus: 'IN_PROGRESS',
      adoptionRate: 0.68,
      searchVolume: 8900,
      difficulty: 6.8,
      createdAt: '2024-01-16',
      description: '各种机器学习算法的研究和应用',
    },
    {
      id: '3',
      keyword: '数据分析平台',
      category: '数据科学',
      priority: 'HIGH',
      optimizationStatus: 'COMPLETED',
      adoptionRate: 0.92,
      searchVolume: 15600,
      difficulty: 5.5,
      createdAt: '2024-01-10',
      description: '企业级数据分析和可视化平台',
    },
    {
      id: '4',
      keyword: '深度学习框架',
      category: '人工智能',
      priority: 'MEDIUM',
      optimizationStatus: 'PENDING',
      adoptionRate: 0.45,
      searchVolume: 6750,
      difficulty: 8.2,
      createdAt: '2024-01-18',
      description: 'TensorFlow, PyTorch等深度学习框架',
    },
  ];

  useEffect(() => {
    loadKeywords();
  }, []);

  const loadKeywords = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      setKeywords(mockKeywords);
    } catch (error) {
      message.error('加载关键词列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 统计数据
  const stats = {
    total: keywords.length,
    completed: keywords.filter(k => k.optimizationStatus === 'COMPLETED').length,
    inProgress: keywords.filter(k => k.optimizationStatus === 'IN_PROGRESS').length,
    averageAdoption: keywords.length > 0 
      ? keywords.reduce((sum, k) => sum + k.adoptionRate, 0) / keywords.length 
      : 0,
  };

  // 表格列定义
  const columns: ColumnsType<Keyword> = [
    {
      title: '关键词',
      dataIndex: 'keyword',
      key: 'keyword',
      width: 200,
      render: (text: string, record) => (
        <div>
          <Text strong style={{ color: '#1890ff' }}>{text}</Text>
          <div style={{ marginTop: 4 }}>
            <Tag color="blue">{record.category}</Tag>
          </div>
        </div>
      ),
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 80,
      render: (priority: string) => {
        const config = priorityConfig[priority as keyof typeof priorityConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '优化状态',
      dataIndex: 'optimizationStatus',
      key: 'optimizationStatus',
      width: 100,
      render: (status: string) => {
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '采用率',
      dataIndex: 'adoptionRate',
      key: 'adoptionRate',
      width: 120,
      render: (rate: number) => (
        <div>
          <Progress
            percent={rate * 100}
            size="small"
            status={rate >= 0.8 ? 'success' : rate >= 0.6 ? 'active' : 'exception'}
            format={(percent) => `${percent?.toFixed(1)}%`}
          />
        </div>
      ),
      sorter: (a, b) => a.adoptionRate - b.adoptionRate,
    },
    {
      title: '搜索量',
      dataIndex: 'searchVolume',
      key: 'searchVolume',
      width: 100,
      render: (volume: number) => volume.toLocaleString(),
      sorter: (a, b) => a.searchVolume - b.searchVolume,
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 80,
      render: (difficulty: number) => (
        <Tag color={difficulty >= 8 ? 'red' : difficulty >= 6 ? 'orange' : 'green'}>
          {difficulty.toFixed(1)}
        </Tag>
      ),
      sorter: (a, b) => a.difficulty - b.difficulty,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: string) => new Date(date).toLocaleDateString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingKeyword(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (keyword: Keyword) => {
    setEditingKeyword(keyword);
    form.setFieldsValue(keyword);
    setIsModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      setKeywords(prev => prev.filter(k => k.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSave = async (values: Keyword) => {
    try {
      if (editingKeyword) {
        setKeywords(prev => prev.map(k => 
          k.id === editingKeyword.id ? { ...k, ...values } : k
        ));
        message.success('更新成功');
      } else {
        const newKeyword: Keyword = {
          ...values,
          id: Date.now().toString(),
          optimizationStatus: 'PENDING' as const,
          adoptionRate: 0,
          createdAt: new Date().toISOString().split('T')[0],
        };
        setKeywords(prev => [newKeyword, ...prev]);
        message.success('添加成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleBatchOptimize = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要优化的关键词');
      return;
    }
    
    try {
      setKeywords(prev => prev.map(k => 
        selectedRowKeys.includes(k.id) 
          ? { ...k, optimizationStatus: 'IN_PROGRESS' as const }
          : k
      ));
      message.success(`开始优化 ${selectedRowKeys.length} 个关键词`);
      setSelectedRowKeys([]);
    } catch (error) {
      message.error('批量优化失败');
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  return (
    <div>
      <Title level={2}>关键词管理</Title>
      
      {/* 统计概览 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="关键词总数"
              value={stats.total}
              prefix={<SearchOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="已完成"
              value={stats.completed}
              valueStyle={{ color: '#3f8600' }}
              prefix={<ArrowUpOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="处理中"
              value={stats.inProgress}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="平均采用率"
              value={(stats.averageAdoption * 100).toFixed(1)}
              suffix="%"
              valueStyle={{ color: stats.averageAdoption >= 0.7 ? '#3f8600' : '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作工具栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col xs={24} sm={8}>
            <Search
              placeholder="搜索关键词"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
          </Col>
          <Col xs={24} sm={16}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加关键词
              </Button>
              <Button 
                icon={<RobotOutlined />}
                disabled={selectedRowKeys.length === 0}
                onClick={handleBatchOptimize}
              >
                批量优化 ({selectedRowKeys.length})
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 关键词列表 */}
      <Card>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={keywords}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加/编辑对话框 */}
      <Modal
        title={editingKeyword ? '编辑关键词' : '添加关键词'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            name="keyword"
            label="关键词"
            rules={[{ required: true, message: '请输入关键词' }]}
          >
            <Input placeholder="输入关键词" />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="category"
                label="分类"
                rules={[{ required: true, message: '请输入分类' }]}
              >
                <Input placeholder="如：人工智能、数据科学" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select placeholder="选择优先级">
                  <Option value="HIGH">高</Option>
                  <Option value="MEDIUM">中</Option>
                  <Option value="LOW">低</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="searchVolume"
                label="搜索量"
                rules={[{ required: true, message: '请输入搜索量' }]}
              >
                <Input type="number" placeholder="月搜索量" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="difficulty"
                label="优化难度"
                rules={[{ required: true, message: '请输入难度' }]}
              >
                <Input type="number" step="0.1" min="0" max="10" placeholder="0-10分" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} placeholder="关键词描述（可选）" />
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingKeyword ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default KeywordManagement;